import logging

import pymysql

from common.loggin import init_log_config


class DBUtil():

    conn=None
    # 创建链接
    @classmethod
    def __create_conn(cls):
        if cls.conn is None:
            cls.conn = pymysql.connect(host="211.103.136.244",port=7061,user="student",password="iHRM_student_2022",
           database="ihrm",charset="utf8")
        return cls.conn
    # 关闭链接
    @classmethod
    def __close_conn(cls):
        if cls.conn is not None:
            cls.conn.close()
            cls.conn=None

    # 查询一条数据的操作
    @classmethod
    def select_one(cls,sql):
        one=None
        cursor=None
        try:
            # 创建链接
            cls.conn = cls.__create_conn()
            # 获取游标
            cursor = cls.conn.cursor()
            # 执行sql
            cursor.execute(sql)
            # 获取结果
            one = cursor.fetchone()
        except Exception as err:
            logging.error(err)
        finally:
            # 关闭游标
            cursor.close()
            # 关闭链接
            cls.__close_conn()
            return one

    # 增删改数据库操作
    @classmethod
    def uid(cls,sql):
        cursor=None
        rows=None
        try:
            # 创链接
            cls.conn = cls.__create_conn()
            # 获取游标
            cursor = cls.conn.cursor()
            # 执行sql
            cursor.execute(sql)
            # 提交commit
            cls.conn.commit()
            rows=cls.conn.affected_rows()
        except Exception as err:
            logging.error(err)
            # 回滚rollback
            cls.conn.rollback()
        finally:
            # 关闭游标
            cursor.close()
            # 关闭链接
            cls.__close_conn()
            return f'受影响的行数:{rows}'